package swingOutput;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;

import javax.swing.JPanel;
import javax.swing.Timer;

import duck.ABlock;
import map.Map;
import base_object.ABaseMoveable;
import base_object.ABaseObject;
import bullet.Bullet;

public class FieldPanel extends JPanel {
	private Image _image=null;
	private Timer t;
	private Map _map;
	boolean move = false;

	public FieldPanel(Map map) {
		Dimension size = getPreferredSize();
		setPreferredSize(size);
		setFocusable(true);
		_map = map;
		addKeyListener((KeyListener) _map.getInput());
		setBackground(Color.GRAY);
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		if(_image == null)
			_image = createImage(624, 673);
		Graphics gImage = _image.getGraphics();
		gImage.fillRect(0, 0, 624, 673);
		
		PriorityQueue<ABaseObject> queue = _map.getQueue();
		for(Iterator<ABaseObject> i = queue.iterator(); i.hasNext();) {
			ABaseObject temp = i.next();
			temp.draw(gImage);
			//System.out.println(temp.toString());
		}
		//System.out.println();
		g.drawImage(_image, 7, 7, this);

	}

	public void repaintFrame() {
		t = new Timer(1000 / 60, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				_map.checkForKill();
				ArrayList<ABaseMoveable> moveable = new ArrayList<ABaseMoveable>();
				for(Iterator<ABaseObject> i = _map.getQueue().iterator(); i.hasNext();){
					ABaseObject temp = i.next();
					if (temp instanceof ABaseMoveable)
						moveable.add((ABaseMoveable) temp);
				}
				for(Iterator<ABaseMoveable> i = moveable.iterator(); i.hasNext();)
					i.next().move();
				repaint();
			}
		});
		t.start();
	}

	public void stopRepainting() {
		t.stop();
	}
}
